package com.uci.photogam.facebook;

import java.util.Hashtable;
import java.util.Stack;



import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.BaseAdapter;


public class FacebookGalleryGetImages{
	Hashtable<String, Bitmap> albumImages;
	Hashtable<String, String> positionRequested;
	BaseAdapter listener;
	int runningCount = 0;
	Stack<Album> queue;
	final static int MAX_ALLOWED_TASKS = 15;

	public FacebookGalleryGetImages()
	{
		albumImages = new Hashtable<String, Bitmap>();
        positionRequested = new Hashtable<String, String>();
        queue = new Stack<Album>();
	}
	
	/*
     * Inform the listener when the image has been downloaded. listener is
     * FriendsList here.
     */
    public void setListener(BaseAdapter listener) {
        this.listener = listener;
        reset();
    }
    
    public void reset() {
        positionRequested.clear();
        runningCount = 0;
        queue.clear();
    }
    
    /*
     * If the profile picture has already been downloaded and cached, return it
     * else execute a new async task to fetch it - if total async tasks >15,
     * queue the request.
     */
    public Bitmap getImage(String uid, String url) {
        Bitmap image = albumImages.get(uid);
        if (image != null) {
            return image;
        }
        if (!positionRequested.containsKey(uid)) {
            positionRequested.put(uid, "");
            if (runningCount >= MAX_ALLOWED_TASKS) {
                queue.push(new Album(uid, url));
            } else {
                runningCount++;
                new UpdateGalleryViewTask().execute(uid, url);
            }
        }
        return null;
    }

    public void getNextImage() {
        if (!queue.isEmpty()) {
            Album item = queue.pop();
            new UpdateGalleryViewTask().execute(item.coverPhotoID, item.link);
        }
    }

	class UpdateGalleryViewTask extends AsyncTask<Object, Void, Bitmap>
	{
		String albumID;

		@Override
		protected Bitmap doInBackground(Object... params) {
			this.albumID = (String) params[0];
			String url = (String) params[1];
			return Utility.getBitmap(url);
		}	
	}

	class Album
	{
		//String id;
		//String name;
		String coverPhotoID;
		String link;

		public Album(String coverPhotoID, String link)//String id, String name, String coverPhotoID, String link)
		{
			//this.id = id;
			//this.name = name;
			this.coverPhotoID = coverPhotoID;
			this.link = link;
		}
	}
}
